package com.maike.babyname.progress;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;

import com.maike.babyname.base.BaseHandler;
import com.maike.babyname.utils.LogUtils;
import com.maike.babyname.utils.UiUtils;
import com.maike.babyname.view.DialogHelper;


public class ProgressDialogHandler extends BaseHandler<Context> {

    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;

    private AlertDialog pd;
//    private ProgressDialog pd;

    private Context context;
    private boolean cancelable;
    private ProgressCancelListener mProgressCancelListener;

    public interface OnDismissListener {
        void onDismiss();
    }

    public ProgressDialogHandler(Context context, ProgressCancelListener mProgressCancelListener,
                                 boolean cancelable) {
        super(context);
        this.context = context;
        this.mProgressCancelListener = mProgressCancelListener;
        this.cancelable = cancelable;
    }

    private void initProgressDialog() {
        if (pd == null) {
            pd = DialogHelper.getInstance().showLoading((Activity) context, "页面加载中,请稍后...", UiUtils.dp2px(context, 160), UiUtils.dp2px(context, 140), true, true);
//            pd = new ProgressDialog(context,android.R.style.Theme_Dialog);
            pd.setMessage("页面加载中,请稍后...");
            pd.setCancelable(cancelable);
            pd.setCanceledOnTouchOutside(false);

            if (cancelable) {
                pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        mProgressCancelListener.onCancelProgress();
                    }
                });
            }

        }
        if (!pd.isShowing()) {
            pd.show();
        }
    }

    public void dismissProgressDialog() {
        LogUtils.e("-------------销毁4");
        if (pd != null) {
            LogUtils.e("-------------销毁5");
            pd.dismiss();

            pd = null;
        }
    }

    @Override
    public void hanlerMessage(Message msg, Context act) {
        LogUtils.e("-------------接受消息------" + msg.what);

        if (!((Activity) context).isFinishing())//xActivity即为本界面的Activity{

            switch (msg.what) {
                case SHOW_PROGRESS_DIALOG:
                    initProgressDialog();
                    break;
                case DISMISS_PROGRESS_DIALOG:
                    LogUtils.e("-------------销毁3");
                    dismissProgressDialog();
                    break;
            }
    }


}
